<?php


namespace app\blog\service;


use app\blog\model\ArticleModel;
use app\blog\model\ArticleTagModel;
use app\blog\Validate\article\GetArticleListByTagIdValidate;
use app\utils\redis\RedisCache;
use app\utils\redis\RedisKey;
use app\utils\redis\RedisObj;

/**
 * 文章控制器的业务逻辑
 * Class ArticleService
 * @package app\blog\service
 */
class ArticleService
{

    /**
     * @param array $param 成功校验通过参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArticleList(array $param) {
        if($param['tag_id']??false){
            return $this->getArticleListByTagId($param);
        }
        return (new ArticleModel())->getArticleList($param);
    }

    /**
     * 根据tag_id获取对应的文章
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getArticleListByTagId($param) {
        $articleTagListPage = (new ArticleTagModel())->where('tag_id', '=', $param['tag_id'])
            ->paginate(['list_rows' => 10, 'page' => $param['page']])
            ->toArray();
        if(empty($articleTagListPage['data'])){
            unset($articleTagListPage['data']);
            $articleTagListPage['lists'] = [];
            return $articleTagListPage;
        }
        // 获取某一页对应文章的id集合
        $articleIds = [];
        foreach ($articleTagListPage['data'] as $value){
            array_push($articleIds, $value['article_id']);
        }
        $lists = (new ArticleModel())->getArticleById($articleIds);
        unset($articleTagListPage['data']);
        $articleTagListPage['lists'] = $lists;
        return $articleTagListPage;
    }

    /**
     * 统计文章的阅读数量，每个ip每天只计算一次
     * @param int $id
     * @param $ip
     * @return bool
     */
    public static function articleReadNum(int $id, $ip) {
        try {
            $key = RedisKey::$articleReadNumKey.$id;
            return RedisCache::wSetAdd(RedisObj::STATISTICS_DB, $key, $ip)===1;
        }catch (\Exception $e) {
            return true;
        }
    }
}